package system.ui;

import system.pojo.Student;
import system.service.StudentService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.List;

public class StudentManagementSystem {
    private StudentService studentService;
    private JFrame frame;
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private int currentPage = 1;
    private int pageSize = 10;
    private String currentKeyword = "";
    private int totalPageCount = 1;

    public StudentManagementSystem() {
        studentService = new StudentService();
        frame = new JFrame("Student Management System");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JPanel topPanel = new JPanel();
        searchField = new JTextField(20);
        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(e -> searchStudents());
        JButton addButton = new JButton("Add");
        addButton.addActionListener(e -> showAddDialog());
        topPanel.add(addButton);
        topPanel.add(searchField);
        topPanel.add(searchButton);
        frame.add(topPanel, BorderLayout.NORTH);

        tableModel = new DefaultTableModel(new Object[]{"ID", "Name", "Age", "Grade", "Actions"}, 0);
        table = new JTable(tableModel);
        table.getColumn("Actions").setCellRenderer(new ButtonRenderer());
        table.getColumn("Actions").setCellEditor(new ButtonEditor(new JCheckBox()));
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new GridLayout(2, 1));

        JPanel navigationPanel = new JPanel();
        JButton prevButton = new JButton("Previous");
        prevButton.addActionListener(e -> previousPage());
        JButton nextButton = new JButton("Next");
        nextButton.addActionListener(e -> nextPage());

        navigationPanel.add(prevButton);
        navigationPanel.add(nextButton);
        bottomPanel.add(navigationPanel);

        frame.add(bottomPanel, BorderLayout.SOUTH);

        loadStudents(currentPage, currentKeyword);
        frame.setVisible(true);
    }

    private void loadStudents(int page, String keyword) {
        try {
            List<Student> students = studentService.searchStudentsByPage(keyword, page, pageSize);
            int totalStudents = studentService.getTotalStudents(keyword);
            totalPageCount = (int) Math.ceil((double) totalStudents / pageSize);

            tableModel.setRowCount(0); // Clear existing rows
            for (Student student : students) {
                tableModel.addRow(new Object[]{student.getId(), student.getName(), student.getAge(), student.getGrade(), "Actions"});
            }

            // Adjust row height to ensure buttons are fully visible
            adjustRowHeight();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void adjustRowHeight() {
        for (int row = 0; row < table.getRowCount(); row++) {
            int rowHeight = table.getRowHeight();

            // Adjust row height to fit button height
            rowHeight = Math.max(rowHeight, 40); // Assuming button height is 40
            table.setRowHeight(row, rowHeight);
        }
    }


    private void searchStudents() {
        currentKeyword = searchField.getText();
        currentPage = 1; // Reset to first page for new search
        loadStudents(currentPage, currentKeyword);
    }

    private void previousPage() {
        if (currentPage > 1) {
            currentPage--;
            loadStudents(currentPage, currentKeyword);
        }
    }

    private void nextPage() {
        if (currentPage < totalPageCount) {
            currentPage++;
            loadStudents(currentPage, currentKeyword);
        }
    }

    private void showAddDialog() {
        AddStudentDialog addStudentDialog = new AddStudentDialog(frame, studentService);
        addStudentDialog.setVisible(true);
        loadStudents(currentPage, currentKeyword);
    }

    private void showUpdateDialog(int id) {
        try {
            Student student = studentService.getStudent(id);
            UpdateStudentDialog updateStudentDialog = new UpdateStudentDialog(frame, studentService, student);
            updateStudentDialog.setVisible(true);
            loadStudents(currentPage, currentKeyword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void deleteStudent(int id) {
        try {
            studentService.deleteStudent(id);
            loadStudents(currentPage, currentKeyword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
//
//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(StudentManagementSystem::new);
//    }

    class ButtonRenderer extends JPanel implements TableCellRenderer {
        private final JButton updateButton = new JButton("Update");
        private final JButton deleteButton = new JButton("Delete");

        public ButtonRenderer() {
            setLayout(new FlowLayout(FlowLayout.CENTER));
            add(updateButton);
            add(deleteButton);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            return this;
        }
    }

    class ButtonEditor extends AbstractCellEditor implements TableCellEditor {
        private JButton updateButton;
        private JButton deleteButton;
        private JPanel panel;
        private int currentEditingRow = -1; // 新增：用于跟踪当前编辑的行索引

        public ButtonEditor(JCheckBox checkBox) {
            updateButton = new JButton("Update");
            deleteButton = new JButton("Delete");
            updateButton.addActionListener(this::updateAction);
            deleteButton.addActionListener(this::deleteAction);
            panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            panel.add(updateButton);
            panel.add(deleteButton);
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            currentEditingRow = row; // 记录当前编辑的行索引
            return panel;
        }

        @Override
        public Object getCellEditorValue() {
            return null; // This method is overridden to satisfy the abstract class
        }

        private void updateAction(ActionEvent e) {
            if (currentEditingRow != -1) { // 确保有有效的行索引
                int id = (int) table.getValueAt(currentEditingRow, 0);
                showUpdateDialog(id);
                fireEditingStopped(); // 停止编辑并刷新表格
            }
        }

        private void deleteAction(ActionEvent e) {
            if (currentEditingRow != -1) { // 确保有有效的行索引
                int id = (int) table.getValueAt(currentEditingRow, 0);
                deleteStudent(id);
                fireEditingStopped(); // 停止编辑并刷新表格
            }
        }
    }


}
